/*
 * @Author: harity
 * @Date: 2021-07-28 17:32:47
 * @LastEditTime: 2021-07-29 15:15:19
 * @LastEditors: Please set LastEditors
 * @Description: EventBus
 * @FilePath: /learn-js/src/eventbus.js
 */

class EventEmeitter {
    constructor() {
        this._events = this._events || new Map()
        this._maxLiteners = this._maxLiteners || 2
    }
}

//监听事件
EventEmeitter.prototype.on = function (type, cb) {
    const handler = this._events.get(type)
    if (!handler) {
        if(this._events.size > this._maxLiteners){
            console.log('caoguo len');
        }else{
            this._events.set(type, [cb])
        }
        
    } else {
        handler.push(cb)
    }
}
//触发事件
EventEmeitter.prototype.emit = function (type) {
    const handler = this._events.get(type)
    if (handler) {
        for (const cb of handler) {
            cb()
        }
    }

}
//移除监听事件
EventEmeitter.prototype.off = function (type) {
    const handler = this._events.get(type)
    if (handler) {
        this._events.delete(type)
    }
}

const myEvent = new EventEmeitter()

myEvent.on('open', function () {
    console.log('open1');
})
myEvent.on('open1', function () {
    console.log('open2');
})
myEvent.on('open2', function () {
    console.log('open3');
})

myEvent.emit('open')

myEvent.off('open')

myEvent.emit('open')

